<template>
  <div class="cluster recovery">
    <a-card style="width:100%">
      <p slot="title" class="cardTitles">
        <span>申请管理</span>
      </p>
      <div class="formDiv">
        <a-form layout="inline" :form="form">
          <a-form-item>
            <a-select
              v-model="keyName"
              :getPopupContainer="triggerNode => triggerNode.parentNode"
              style="width:130px"
            >
              <a-select-option value="2">全部</a-select-option>
              <a-select-option value="login_name">用户名</a-select-option>
              <a-select-option value="mobile">手机号</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-input v-model="searchWord" type="text" style="width: 180px;" />
          </a-form-item>
          <a-form-item>
            <a-button @click="search()" type="primary">搜索</a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="reset()">重置</a-button>
          </a-form-item>
        </a-form>
        <div class="operation-btn">
          <a-button type="primary" @click="addUser()" style="margin-right:15px;">新增</a-button>
          <a-button type="danger" @click="remove()">删除</a-button>
        </div>
      </div>
      <div style="margin-top:10px">
        <a-table
          :loading="loading"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="list"
          rowKey="id"
          :pagination="pagination"
          @change="changePage"
        >
          <template slot-scope="text,record" slot="channel">
            <span>{{record.channel|userChannel}}</span>
          </template>
          <template slot-scope="text,record" slot="type">
            <span>{{record.type|userType}}</span>
          </template>
          <template slot-scope="text,record" slot="state">
            <a-badge
              :color="record.state == 0?'#87d068': record.state == 1? 'orange' : record.state == 2 ? '#2db7f5' : '#f50'"
              :text="record.state|userState"
            ></a-badge>
          </template>
          <template slot-scope="text,record" slot="action">
            <a
              class="tools"
              @click="audit(record)"
              v-if="record.state == 1 || record.state == -1"
            >审核</a>
            <a class="tools" type="link" @click="formDetail(record)" v-if="record.state != 2 ">查看</a>
            <a class="tools" @click="editUser(record)" v-if="record.state == 2">编辑</a>
            <a class="tools" type="link" @click="remove(record)" v-if="record.state == 2">删除</a>
          </template>
        </a-table>
      </div>
    </a-card>
    <div class="modal-content">
      <!-- 新增 or 编辑-->
      <a-modal
        :title="modalTitle"
        width="800px"
        centered
        :visible="userinformVisible"
        :maskClosable="false"
        @cancel="close"
      >
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          v-bind="formLayout"
          class="inform-form"
          style="height:auto;"
        >
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="用户名" prop="loginName">
                <a-input v-model="form.loginName" :maxLength="16" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="密码" prop="password">
                <a-input-password ref="password" v-model="form.password" style="width:64%"></a-input-password>
                <a-button
                  type="primary"
                  @click="getDefaultPassword()"
                  style="float:right;margin-top:4px"
                >初始密码</a-button>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="手机号" prop="mobile">
                <a-input v-model="form.mobile" autocomplete="off" :maxLength="11" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="单位信息" prop="unitName">
                <a-input v-model="form.unitName" autocomplete="off" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="邮箱" prop="email">
                <a-input v-model="form.email" autocomplete="off" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="渠道" prop="channel">
                <a-select v-model="form.channel" @change="handleChange" disabled>
                  <a-select-option :value="0">线上</a-select-option>
                  <a-select-option :value="1">线下</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="用户类型" prop="type">
                <a-radio-group v-model="form.type" @change="onRadioChange">
                  <a-radio :value="1">独立机构</a-radio>
                  <a-radio :value="0">普通用户</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="机构名称" prop="rootId" v-if="form.type == 1">
                <a-auto-complete
                  v-model="form.rootId"
                  backfill
                  autofocus
                  :filter-option="filterOption"
                  placeholder="请输入机构名称"
                  @select="onSelect"
                  @search="onSearch"
                  @change="onChange"
                >
                  <template slot="dataSource">
                    <a-select-option v-for="item in unitList" :key="item.id">{{ item.unitName }}</a-select-option>
                  </template>
                </a-auto-complete>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                label="是否短信"
                prop="sendSms"
                :label-col="{span:3}"
                :wrapper-col="{span:21}"
              >
                <a-switch :checked="form.sendSms == 0" @change="onCheckdChange" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <template slot="footer">
          <a-button @click="submitInform('form', 2)">暂存</a-button>
          <a-button type="primary" @click="submitInform('form', 1)">确定</a-button>
        </template>
      </a-modal>
      <!-- 审核 -->
      <a-modal
        :title="modalTitle"
        width="600px"
        :visible="userApplicationVisible"
        :maskClosable="false"
        @cancel="closeApplicationModal"
      >
        <div>
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="用户名">{{form.loginName}}</a-descriptions-item>
            <a-descriptions-item label="手机号">{{form.mobile}}</a-descriptions-item>
            <a-descriptions-item label="单位信息">{{form.unitName}}</a-descriptions-item>
            <a-descriptions-item label="邮件">{{form.email}}</a-descriptions-item>
            <a-descriptions-item label="渠道">{{form.channel | userChannel}}</a-descriptions-item>
            <a-descriptions-item label="申请时间">{{form.applyTime}}</a-descriptions-item>
            <a-descriptions-item label="用户类型">{{form.type|userType}}</a-descriptions-item>
            <a-descriptions-item label="是否短信">
              <a-switch :disabled="true" :checked="form.sendSms == 0" />
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <template slot="footer" v-if="optFlag===4">
          <a-button @click="auditSubmit(-1)">不通过</a-button>
          <a-button type="primary" @click="auditSubmit(0)">通过</a-button>
        </template>
        <template slot="footer" v-else>
          <a-button @click="closeApplicationModal()">取消</a-button>
        </template>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { paging } from "assets/js/mixin";
import {
  list,
  add,
  update,
  audit,
  getUnitList,
  remove,
  detail,
} from "@/api/application";
import { getDefaultPassword } from "@/api/system";
export default {
  mixins: [paging],
  data() {
    return {
      loading: false,
      optFlag: 1, //1是新增2是编辑3是查看4是审核
      modalTitle: "", //弹窗标题
      userinformVisible: false,
      userApplicationVisible: false,
      id: "",
      keyName: "2",
      searchWord: "",
      numbers: 0,
      selectedRowKeys: [],
      columns: [
        {
          title: "用户名",
          dataIndex: "loginName",
          width: "120px",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          width: "130px",
        },
        {
          title: "单位信息",
          dataIndex: "unitName",
          width: "120px",
        },
        {
          title: "申请时间",
          dataIndex: "applyTime",
          width: "180px",
        },
        {
          title: "邮件",
          dataIndex: "email",
          width: "220px",
        },
        {
          title: "渠道",
          dataIndex: "channel",
          scopedSlots: { customRender: "channel" },
          width: "80px",
        },
        {
          title: "类型",
          dataIndex: "type",
          scopedSlots: { customRender: "type" },
          width: "100px",
        },
        {
          title: "状态",
          dataIndex: "state",
          scopedSlots: { customRender: "state" },
          width: "100px",
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          width: "120px",
        },
      ],
      list: [],
      unitList: [],
      rules: {
        unitList: [
          { required: true, message: "请选择所属机构", trigger: "change" },
        ],
        loginName: [
          {
            validator: (rule, value, callback) => {
              const regg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
              //const replaceReg = /[^\\x00-\\xff]/;
              var len = value.replace(/[^\x00-\xff]/g, "aa").length;
              if (value && !regg.test(value)) {
                callback(new Error("请输入汉字/英文/数字, 不包含特殊符号"));
              } else{
                callback();
              } 
            },
            trigger: ["blur", "change"],
          },
          
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              const whiteSpace = /^[a-zA-Z0-9]{4,10}$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("密码不能含有非法字符，长度在4-10之间"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        mobile: [
          {
            max: 11,
            message: "长度不合法, 手机号限11位",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              const number = /^[0-9]+$/;
              if (value && !number.test(value)) {
                callback(new Error("只允许输入数字"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1(3|4|5|6|7|8)\d{9}$/,
            message: "请输入正确的手机号",
          },
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              const whiteSpace = /^[^ ]+$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("输入内容不能有空格"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            required: false,
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: "请输入正确格式的邮箱",
            trigger: "blur",
          },
        ],
        rootId: [
          {
            validator: (rule, value, callback) => {
              const whiteSpace = /^[^ ]+$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("输入内容不能有空格"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            required: true,
            message: "请输入机构名称",
            trigger: "blur",
          },
        ],
      },
      formLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      form: {
        id: "",
        password: "",
        sendSms: "1",
        type: 0,
        unitName: "",
        email: "",
        loginName: "",
        mobile: "",
        rootId: "",
        channel: 1,
      },
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "form" });
  },
  mounted() {
    this.getlist();
  },
  methods: {
    close() {
      this.userinformVisible = false;
    },
    closeApplicationModal() {
      this.userApplicationVisible = false;
    },

    //获取初始密码
    getDefaultPassword() {
      getDefaultPassword().then((res) => {
        this.form.password = res.data.data;
        this.$refs.password.visible = true;
      });
    },
    //获取数据
    getlist() {
      this.loading = true;
      var params = {
        searchWord: this.searchWord,
        filterColumns: [],
        current: this.pageNum,
        size: this.pageSize,
      };
      if (this.keyName != "2") {
        params.filterColumns.push(this.keyName);
      }
      list(params)
        .then((res) => {
          this.list = res.data.data.records;
          this.pagination.total = res.data.data.total;
          this.loading = false;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //搜索
    search() {
      this.pageNum = 1;
      this.pagination.current = 1;
      this.getlist();
    },
    //重置
    reset() {
      this.keyName = "2";
      this.searchWord = "";
      this.pageNum = 1;
      this.pagination.current = 1;
      this.getlist();
    },
    //编辑
    editUser(record) {
      this.id = record.id;
      this.userinformVisible = true;
      this.optFlag = 2;
      this.modalTitle = "用户申请信息编辑";
    },
    //新增
    addUser() {
      this.userinformVisible = true;
      this.optFlag = 1;
      this.modalTitle = "用户申请信息填报";
      this.id = "";
    },
    //查看
    formDetail(record) {
      //查看用户信息
      this.userApplicationVisible = true;
      this.optFlag = 3;
      this.modalTitle = "查看";
      this.id = record.id;
    },
    //审核
    audit(record) {
      this.userApplicationVisible = true;
      this.optFlag = 4;
      this.modalTitle = "审核";
      this.id = record.id;
    },
    //表单提交
    submitInform(formName, state) {
      this.form.state = state;
      this.loading = true;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.loading = false;
          return false;
        }
      });
      if (this.loading) {
        var params = Object.assign({}, this.form);
        //根据params.rootId去查询机构，如果有就不做任何操作，如果灭有就新增
        if (this.optFlag == 2) {
          params.id = this.id;
          // 编辑提交
          this.updateSubmit(params);
        } else {
          //新增提交
          this.addSubmit(params);
        }
      }
    },
    addSubmit(params) {
      add(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success(res.data.msg);
          this.userinformVisible = false;
          this.getlist();
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    updateSubmit(params) {
      update(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success(res.data.msg);
          this.userinformVisible = false;
          this.getlist();
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //是否通过
    auditSubmit(isPass) {
      let data = {
        id: this.id,
        isPass: isPass,
        sendSms: this.form.sendSms,
      };
      audit(data).then((res) => {
        this.$message.destroy();
        this.userApplicationVisible = false;
        this.$message.success(res.data.msg);
        this.getlist();
      });
    },
    remove(record) {
      let ids = [];
      var _this = this;
      if (!record && this.selectedRowKeys.toString().length == 0) {
        _this.$message.destroy();
        _this.$message.warning("请在列表中选择要操作的记录！");
        return;
      }
      if (!record) {
        _this.numbers = this.selectedRowKeys.length;
        ids = this.selectedRowKeys;
      } else {
        _this.numbers = 1;
        ids.push(record.id);
      }
      //列表删除操作
      this.$confirm({
        title: "您是否确认要删除所选中的记录？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          remove(ids)
            .then(() => {
              _this.$message.destroy();
              _this.$message.success("操作成功");
              _this.deleteAfterPageNum(_this.numbers);
              _this.getlist();
            })
            .catch((err) => {
              _this.$message.destroy();
              _this.$message.error(err);
            });
        },
      });
    },
    //获取独立机构列表
    getUnitList() {
      getUnitList().then((res) => {
        this.unitList = res.data.data;
      });
    },
    getData() {
      //获取页面数据
      detail(this.id)
        .then((res) => {
          this.form.loginName = res.data.data.loginName;
          this.form.email = res.data.data.email;
          this.form.mobile = res.data.data.mobile;
          this.form.password = res.data.data.password;
          this.form.sendSms = res.data.data.sendSms;
          this.form.channel = res.data.data.channel;
          this.form.state = res.data.data.state;
          this.form.unitName = res.data.data.unitName;
          this.form.type = res.data.data.type;
          this.form.applyTime = res.data.data.applyTime;
          this.form.rootId = res.data.data.rootId;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //机构名称
    onSearch(searchText) {
      if (this.form.rootId) {
        this.form.rootId = searchText;
      }
    },
    onSelect(value) {
      this.form.rootId = value;
    },
    //机构名称下拉框选择
    onChange(val) {
      this.form.rootId = val;
    },
    //机构名称模糊输入列表筛选
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //渠道下拉框选择
    handleChange(value) {
      this.form.channel = value;
    },
    //用户类型单选改变
    onRadioChange(e) {
      if (e.target.value == 0) {
        this.rules.rootId = [
          {
            validator: (rule, value, callback) => {
              const whiteSpace = /^[^ ]+$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("输入内容不能有空格"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            required: false,
            message: "请输入机构名称",
            trigger: "blur",
          },
        ];
      } else {
        this.rules.rootId = [
          {
            required: true,
            validator: (rule, value, callback) => {
              const whiteSpace = /^[^ ]+$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("输入内容不能有空格"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            required: true,
            whitespace: true,
            message: "请输入机构名称",
            trigger: "blur",
          },
        ];
      }
    },
    //类型单选按钮选择
    onCheckdChange(checked) {
      if (checked) {
        this.form.sendSms = 0;
      } else {
        this.form.sendSms = 1;
      }
    },
    //分页
    changePage(pagination) {
      this.pageNum = pagination.current;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getlist();
    },
    //列表多选操作
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
  },
  watch: {
    userinformVisible(n) {
      if (n) {
        //调用查询接口
        this.getUnitList();
        if (this.id) {
          //获取
          this.getData(this.id);
        } else {
          this.form = {
            id: "",
            password: "",
            sendSms: "1",
            type: 0,
            unitName: "",
            email: "",
            loginName: "",
            mobile: "",
            rootId: "",
            channel: 1,
          };
        }
      } else {
        this.$refs["form"].resetFields();
        this.$refs.password.visible = false;
      }
    },
    userApplicationVisible(n) {
      if (n) {
        if (this.id) {
          //获取
          this.getData(this.id);
        }
      }
    },
  },
};
</script>
<style lang="stylus" scoped>
.recovery {
  a.detail {
    color: #66b1ff;
  }

  .formDiv {
    position: relative;
  }

  .operation-btn {
    position: absolute;
    top: 4px;
    right: 0;
  }

  a.detail:hover {
    text-decoration: underline;
  }
}
</style>